(function( $, undefined ) {

$.widget("ui.ajajform_largeselect",$.ui.ajajform_widget, {
	options: {
		// \type cssclass
		cssclass: "afw-largeselect",
		value: {},
		action: null,
		values: [],
		dialog_title: "",
		dialog_width: 600, 
		page_width: 500,
		dialog_height: 500,
		multiselect: false,
		label: "",
		save: "checkboxlist",// json, csv or checkboxlist
		html: false,
		width: null,
		notnull: false,
		empty: "",
		htmltemplate_single: '<div class="af-label"></div><div class="af-value"><div class="af-item"></div><div class="af-error"></div></div><div class="af-button af-button-edit"></div><div style="clear: both;"></div>',
		htmltemplate_multiselect: '<div class="af-label"></div><div class="af-value"><div class="af-items"></div><div class="af-buttons-add"><div class="af-button af-button-add"></div><div style="clear: both;"></div><div class="af-error"></div></div></div><div style="clear: both;"></div>',
		readonly: false
	},

	i18n: {
		ru: {create_button:"Создать",edit_button:"Сохранить",err_empty:"Поле должно быть заполнено",save_button:"Сохранить",back_button:"Назад"},
		en: {create_button:"Create",edit_button:"Save",err_empty:"Field must be filled",save_button:"Save",back_button:"Back"}
	},

	_create: function() {
		this.element.addClass(this.options.cssclass);
		this.element.append(this.options.multiselect?this.options.htmltemplate_multiselect:this.options.htmltemplate_single);
		this.refreshLabel();
		this.refreshWidth();
		var t=this;	
		$(".af-button",this.element).bind("click",function() {t.newEditClicked();});
		this.refreshValue();
		this.refreshReadonly();
	},


	refreshReadonly: function() {
		if (this.options.readonly) this.element.addClass("afw-largeselect-read-only"); else  this.element.removeClass("afw-largeselect-read-only");
	},

	newEditClicked: function() {
		if (this.options.readonly) return;
		var val;
		if (!this.options.multiselect) val=this.options.value;
		this.popupOpen(val?val.id:undefined);
	},

	editClicked: function(i) {
		if (this.options.readonly) return;
		var v;
		if (this.options.multiselect) v=this.options.values[i].id; else v=this.options.value;
		this.popupOpen(v);
	},
	
	urlAttach: function() {
		if (this.options.action.match(/[?&]$/)) return this.options.action;
		if (this.options.action.match(/\?/)) return this.options.action+"&";
		return this.options.action+"?";
	},

	popupOpen: function(val) {
		console.log({func:"popupOpen",val:val,value:this.options.value,values:this.options.values});
		var t=this;
		var id=0;
		while ($("#dialogdiv"+id).length) id++;
		var tmp1;
		tmp1=$("<div id='dialogdiv"+id+"' class='afw-dialog-largeselect'></div>").appendTo($("body"));
		this.dialogid=id;
		tmp1.dialog({
			title:this.options.dialog_title,
			width:this.options.dialog_width,
			height:this.options.dialog_height,
			close: function(event, ui) {
				t.popupClose();
			},
			modal: true
		});
		tmp1.html("<div class='af-pages'></div>"+(this.options.multiselect?"<div class='af-bottomline'><input type='button' class='save'/></div>":""));
		if (this.options.multiselect) $(".save",tmp1).attr("value",this.gettext("save_button")).button().bind("click",function() {t.popupClose();});
		this.pagenow=0;
		this.pagemax=0;
		if (val) {
			$("#dialogdiv"+this.dialogid+" .af-pages").html("<div class='af-loading'></div>");
			$.ajax({
				method: "GET",
				url: this.urlAttach()+"pathof="+val,
				dataType: "json",
				success: function (r) {
					$("#dialogdiv"+t.dialogid+" .af-loading").remove();
					t.popupUpdatePagenow(r.path.length-1);
					t.popupLoad(r.path);
				}
			});
		} else {
			this.popupLoad([null]);
		}
	},


	popupLoad: function(ids) {
		var t=this;
		var pagestart=this.pagemax;
		for (var i=0;i<ids.length;i++) {	
			$("<div class='af-page af-page-"+this.pagemax+"'></div>").appendTo($("#dialogdiv"+this.dialogid+" .af-pages")).css({top:0, left:this.pagemax*(this.options.page_width+10), width: this.options.page_width}).html("<div class='af-loading'></div>");
			this.pagemax++;
		}
		$.ajax({
			method: "GET",
			url: this.urlAttach()+"parent_id="+ids.join(","),
			dataType: "json",
			success: function(r) { t.popupLoaded(r,pagestart); }
		});
	},
	

	popupLoaded: function(r,pagestart) {
		for (var i=0;i<r.levels.length;i++) {
			this.popupRenderPage(r.levels[i],i+pagestart);
		}
	},


	getSelectedHash: function(items,pn) {
		var h={};
		if (this.options.multiselect) {
			if (this.options.values) {
				for (var i=0;i<this.options.values.length;i++) {
					h[this.options.values[i].id]=1;
				}
			}
		} else {
			if (this.options.value && this.options.value.id) h[this.options.value.id]=1;
		}
		return h;
	},


	popupRenderPage: function(items,pn) {
		var t=this;
		var selected=this.getSelectedHash();
		var pdiv=$("#dialogdiv"+this.dialogid+" .af-page-"+pn);
		console.log({func:'renderpage',items:items,pn:pn,pdiv:pdiv,dialogid:this.dialogid});
		pdiv.empty();
		pdiv.append("<div class='af-buttons'></div><div class='af-items'></div>");
		if (pn) $("<div class='af-button-back'></div>").text(t.gettext("back_button")).appendTo($(".af-buttons",pdiv)).bind("click",function() { t.popupBackClicked(); });
		var iidiv=$(".af-items",pdiv);
		for (var i=0;i<items.length;i++) {
			var idiv=$("<div class='af-item'><div class='af-button af-button-select'></div><div class='af-button af-button-inside'></div><div class='af-text'></div><div class='cl'></div></div>").appendTo(iidiv);
			$(".af-text",idiv).text(items[i].name);
			if (selected[items[i].id]) idiv.addClass("af-itemSelect");
			if (!items[i].can_select) $(".af-button-select",idiv).hide();
			if (!items[i].can_inside) $(".af-button-inside",idiv).hide();
			if (items[i].can_inside) {
				if (items[i].can_select) {
					$(".af-button-inside",idiv).bind("click",{id:items[i].id,pn:pn},function(e) { t.popupGoInside(e.data.id,e.data.pn,$(this.parentNode)); });
					$(".af-button-select",idiv).bind("click",{item:items[i],pn:pn},function(e) { t.popupSwitchSelect(e.data.item,e.data.pn,$(this.parentNode)); });
				} else {
					idiv.bind("click",{id:items[i].id,pn:pn},function(e) { t.popupGoInside(e.data.id,e.data.pn,$(this)); });
				}
			} else if (items[i].can_select) {
				idiv.bind("click",{item:items[i],pn:pn},function(e) { t.popupSwitchSelect(e.data.item,e.data.pn,$(this)); });
			}
		}
	},


	popupClose: function() {
		$("#dialogdiv"+this.dialogid).remove();
		this.refreshValue();
	},


	popupSwitchSelect: function(item,pn,idiv) {
		if (!this.options.multiselect) {
			this.options.value=item;
			this.popupClose();
			this.refreshValue();
			return;
		}
		var i=0;
		while (i<this.options.values.length) {
			if (this.options.values[i].id==item.id) {
				this.options.values.splice(i,1);
				idiv.removeClass("af-itemSelect");
				return;
			}
			i++;
		}
		this.options.values.push(item);
		idiv.addClass("af-itemSelect");
//		this.options.refresh
	},


	popupDeleteExtraPages: function(pn) {
		while (this.pagemax>pn) {
			this.pagemax--;
			$("#dialogdiv"+this.dialogid+" .af-page-"+this.pagemax).remove();
		}
	},

	popupBackClicked: function() {
		if (this.pagenow==0) return;
		this.popupDeleteExtraPages(this.pagenow);
		this.popupUpdatePagenow(this.pagenow-1);
		if (this.pagemax) $("#dialogdiv"+this.dialogid+" .af-page-"+(this.pagemax-1)+" .af-itemInside").removeClass("af-itemInside");
	},

	popupGoInside: function(id,pn,item) {
		$(".af-itemInside",item.parent()).removeClass("af-itemInside");
		item.addClass('af-itemInside');
		this.pagenow=pn+1;
		this.popupDeleteExtraPages(pn+1);
		this.popupUpdatePagenow(pn+1);
		this.popupLoad([id]);
	},


	popupUpdatePagenow: function(pn) {
		this.pagenow=pn;
		$("#dialogdiv"+this.dialogid+" .af-pages").animate({scrollLeft:this.pagenow==0?0:((this.options.page_width+10)*this.pagenow-50)},1000);
//		$("#dialogdiv"+this.dialogid+" .af-pages").animate({"margin-left":this.pagenow==0?0:(50-(this.options.page_width+10)*this.pagenow)});
	},

	refreshWidth: function() {
		if (this.options.multiselect) {
			$(".af-value",this.element).width(this.options.width);
			$(".af-value2",this.element).width(this.options.width);
		} else {
			$(".af-value",this.element).width(this.options.width-19);
			$(".af-value2",this.element).width(this.options.width-19);
		}
	},


	refreshLabel: function() {
		$(".af-label",this.element).text(this.options.label);
	},


	refreshValue: function() {
		var t=this;
		if (this.options.multiselect) {
			var div=$(".af-value .af-items",this.element);
			var v=this.options.values;
			div.empty();
			for (var i=0;i<v.length;i++) {
				var div2=$("<div class='af-item'><div class='af-content'></div><div class='af-button-edit'></div><div class='af-button-delete'></div><div class='cl'></div></div>").appendTo(div);
				$(".af-content",div2)[this.options.html?"html":"text"](v[i].fullname||v[i].name).width(this.options.width-19*2);
				$(".af-button-delete",div2).bind("click",{i:i},function(e) {t.options.values.splice(e.data.i,1);t.refreshValue();});
				$(".af-button-edit",div2).bind("click",{i:i},function(e) {t.editClicked(e.data.i)});
			}
			if (v.length==0) div.text(this.options.empty);
		} else {
			var div=$(".af-value .af-item",this.element);
			var v=this.options.value;
			div[this.options.html?"html":"text"](v.fullname||v.name);
		}
	},

	postvalue: function(r) {
		switch (this.options.save) {
			case "checkboxlist":
				if (this.options.multiselect) {
					for (var i=0;i<this.options.values.length;i++) r[this.options.name+"-"+this.options.values[i].id]=1;
				} else {
					if (this.options.value && this.options.value.id) r[this.options.name+"-"+this.options.value.id]=1;
				}
				break;
			case "json":
			case "csv":
				if (this.options.multiselect) {
					var arr=[];
					for (var i=0;i<this.options.values.length;i++) arr.push(this.options.values[i].id);
					r[this.options.name]=this.options.save=="json"?JSON.stringify(arr):arr.join(",");
				} else {
					if (this.options.value && this.options.value.id) r[this.options.name]=this.options.value.id;
				}
				break;
		}
	},

	validate: function() {
		var vd=this.options.validate;
		var r;
		if (vd) r=vd(this.options.multiselect?this.options.values:this.options.value);
		if (!r) {
			if (this.options.notnull) {
				if (this.options.multiselect) {
					if (!this.options.values ||this.options.values.length==0) r=this.gettext("err_empty");
				} else {
					var i;
					if (this.options.value) for (var k in this.options.value) i=1;
					if (!i) r=this.gettext("err_empty");
				}
			}
		}
		this.refreshError(r);
		return r?true:false;
	}
});

})( jQuery );


